import React, { useState, useEffect, Fragment, useCallback } from 'react';
import { message, Checkbox, Button, Image, Modal, Select, Tag } from 'antd';
import { connect } from 'umi';
import { getAuthority } from '@/utils/authority';
import { LeftOutlined } from '@ant-design/icons';
const { Option } = Select;
const CheckboxGroup = Checkbox.Group;

import './index.less';
// 默认头像
import default_avatar from '@/assets/default_avatar.png';
import next from '@/assets/homePage/next.png';
import check from '@/assets/common/check.png';
import checked from '@/assets/common/checked.png';
import { debounce } from '@/utils/utils';

// 全局变量
const ossUrl = process.env.OSS_URL;

const SelectPerson = (props: {
    dispatch?: any;
    visible: boolean;
    onClose: ()=>void;
    onCallBack: (e:any[])=>void;
    initData?: Array<{
        id: string;
        logo: string;
        userName: string;
    }>;
}) => {
    const { dispatch, initData, visible, onClose, onCallBack } = props;
    // 用户信息
    const loginInfo: any = getAuthority();
    
    // title默认显示这个老师所在学校
    const [title, setTitle] = useState<string>(loginInfo.orgName);
    // 是否全选
    const [isSelectAll, setIsSelectAll] = useState<boolean>(false);
    // 页面上显示的类别：专业list、人员list
    const [type, setType] = useState<'major' | 'person'>('major');
    // 搜索出来的人员列表
    const [searchPersonList, setSearchPersonList] = useState<any[]>([]);
    
    // 专业列表
    const [majorList, setMajorList] = useState<any[]>([]);
    // 人员列表
    const [personList, setPersonList] = useState<any[]>([]);
    // 已选专业 id 列表
    // const [selectMajorList, setSelectMajorList] = useState<any[]>([]);

    // 已选人员 列表 左侧渲染用的
    const [selectPersonList, setSelectPersonList] = useState<any[]>([]);
    
    useEffect(() => {
        // 选人组件 - 老师专业列表
        if(visible)  getMajorIdByTeacherId(); 
        // 把所有同学都加载出来
        getStudentByMajorId(null, '', (data)=>{
            setSearchPersonList(data);
        });
    }, [visible]);

    useEffect(()=>{
        if(Array.isArray(initData) && initData.length > 0){
            setSelectPersonList(initData);
        }
    }, [initData]);


    useEffect(()=>{
        if(Array.isArray(selectPersonList) && selectPersonList.length > 0){
            let _selectPersonList = JSON.parse(JSON.stringify(selectPersonList));
            // 去重
            let list = []; // 存放去重过后的数据
            let obj = {}; // 去除data,里面 id 相同的对象
            for (var i = 0; i < _selectPersonList.length; i++) {
                if (!obj[_selectPersonList[i].id]) {
                    list.push(_selectPersonList[i])
                    obj[_selectPersonList[i].id] = true
                } 
            }

            setSelectPersonList(list);
        }
        
    }, [selectPersonList.length]);

    // 选人组件 - 老师专业列表
    const getMajorIdByTeacherId = () => {
        dispatch({
            type: 'common/getMajorIdByTeacherId',
            payload: {},
            callback: (res: any) => {
                const { code, data = [], msg } = res;
                if (code === 1) {
                    setMajorList(data);
                } else {
                    message.error(msg || '服务器开小差了~');
                }
            },
        });
    }

    // 选人组件 - 根据专业获取对应学生
    const getStudentByMajorId = (majorIds: string[], userName: string, callBack: (e:any[])=>void) => {
        dispatch({
            type: 'common/getStudentByMajorId',
            payload: { majorIds, userName },
            callback: (res: any) => {
                const { code, data = [], msg } = res;
                if (code === 1) {
                    callBack(data);
                } else {
                    message.error(msg || '服务器开小差了~');
                }
            },
        });
    }

    // 点击全选
    const onAllRadioChange = (e:any)=>{
        setIsSelectAll(e.target.checked);
        
        if(e.target.checked){
            // 全选
            if(type === 'major') {
                setMajorList(majorList.map(v=>({...v, checked: true})));
                getStudentByMajorId(majorList.map(v=>v.value), '', (data)=>{
                    setSelectPersonList(data);
                });
            } else {
                let _personList = JSON.parse(JSON.stringify(personList));
                _personList = _personList.map(v=>({...v, checked: true}));
                setPersonList(_personList);
                setSelectPersonList([...selectPersonList, ..._personList]);
            }
            
        } else {
            // 全反选
            if(type === 'major') {
                setMajorList(majorList.map(v=>({...v, checked: false})));
                setSelectPersonList([]);
            } else {
                setPersonList(personList.map(v=>({...v, checked: false})));
                // 从 selectPersonList 中 删除当前人员列表
                const _list = selectPersonList.filter(v=>personList.findIndex(j=>j.id === v.id) < 0);
                setSelectPersonList(_list);
            }
            
        }
    }

    // 选择专业、人员
    const onCheckSelectChange = (item:any, index: number) => {
        console.log('onCheckSelectChange', item, index);
        if(type === 'major') { // 选择专业
            let _majorList = JSON.parse(JSON.stringify(majorList));
            _majorList[index].checked = item.checked ? false : true;
            
            setMajorList(_majorList);
            // 重新查询所选人员
            getStudentByMajorId([item.value], '', (data)=>{
                let _selectPersonList = JSON.parse(JSON.stringify(selectPersonList));
                if(item.checked) {
                    setSelectPersonList(_selectPersonList.filter(v=>data.findIndex(j=>j.id === v.id) < 0));
                } else {
                    setSelectPersonList([..._selectPersonList, ...data]);
                }
            });

            // 检测是否需要全选
            setIsSelectAll(_majorList.length === _majorList.filter((v:any)=>v.checked === true).length)
            
        } else { // 选择人员
            let _personList = JSON.parse(JSON.stringify(personList));
            let _selectPersonList = JSON.parse(JSON.stringify(selectPersonList));
            _personList[index].checked = item.checked ? false : true;
            setPersonList(_personList);
            
            if(item.checked){
                _selectPersonList = _selectPersonList.filter(v=>v.id !== item.id);
                setSelectPersonList(_selectPersonList);
            } else {
                console.log([..._selectPersonList, item])
                
                setSelectPersonList([..._selectPersonList, item]);
            }

            // 检测是否需要全选
            setIsSelectAll(_personList.filter(v=>v.checked === true).length === _personList.length)
        }

    };

    const onBack = ()=>{
        setType('major');
        setTitle(loginInfo.orgName);
    }

    const goNext = (e:any, v:{ value: string; label: string;})=>{
        e.stopPropagation();
        setIsSelectAll(false);
        setType('person');
        getStudentByMajorId([v.value], '', (data)=>{
            // 校验data是不是在已选人员列表里，如果全在，将全选勾上,
            let _data = data.map(f=>({ ...f, checked: selectPersonList.findIndex(g=>g.id === f.id) > -1 }));
            setPersonList(_data.map((v:any)=>({ ...v, value: v.id })));
            // 检测是否需要将全选勾上后者取消勾选
            setIsSelectAll(data.length === _data.filter(v=>v.checked === true).length);
        });
        setTitle(v.label);
    }

    const onSearch = (value:any)=> {
        console.log('onSearch:', value);
        
    }

    const onSearchChange = (value:any)=>{
        console.log('onSearchChange:', value);
        // 如果选中了某一项
        if(value) {
            if(type === 'person') {
                // 校验当前人员列表里有没有这个人，如果有，标识选中
                const _personList = JSON.parse(JSON.stringify(personList));
                setPersonList(_personList.map(v=>({...v, checked: v.checked || v.id === value})));
                // 将搜索之后选中的这一项数据插入到 selectPersonList 里去
                const currentPerson = searchPersonList.filter(v=>v.id === value);
                setSelectPersonList([...selectPersonList, ...currentPerson])
            } else {
                const _searchPersonList = JSON.parse(JSON.stringify(searchPersonList));
                setSelectPersonList([...selectPersonList, ..._searchPersonList.filter(v=>v.id === value)]);
            }
        }
    }

    const onCancel = ()=> {
        onClose();
    }
    const onOk = ()=> {
        onClose();
        onCallBack(selectPersonList);
    }

    // 左侧删除某一个已选的人
    const closeOnePerson = (item:any)=>{
        // 删除已选里的这个人
        setSelectPersonList(selectPersonList.filter((v:any)=>v.id !== item.id));
    }

    return (
		<Modal
            title={'选择人员'}
            className='selectPersonModalWrap'
            closable
            width={1000}
            maskClosable={false}
            visible={visible}
            footer={null}
            onCancel={onClose}
        >
            <div className='mainDiv'>
                {/* 左侧 */}
                <div>
                    {
                        selectPersonList.map(v=><Tag closable onClose={(e)=>closeOnePerson(v)}>{v.userName}</Tag>)
                    }
                    
                    
                    <Select
                        showSearch
                        placeholder="请输入姓名搜索"
                        optionFilterProp="children"
                        onChange={onSearchChange}
                        onSearch={onSearch}
                        filterOption={(input, option) =>option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                    >
                        {
                            searchPersonList.map(v=><Option value={v.id}>{v.userName}</Option>)
                        }
                    </Select>
                </div>
                {/* 右侧 */}
                <div>
                    <h1 className='title'>
                        {type === 'person' && <LeftOutlined onClick={onBack} />}
                        {title}
                    </h1>
                    <div className='selectRadio'>
                        <Checkbox checked={isSelectAll} onChange={onAllRadioChange}>全选</Checkbox>
                    </div>
                    <div className='list'>
                        <div>
                            {
                                type === 'major' && majorList.map((v, i)=><div className='checkboxItem' onClick={()=>onCheckSelectChange(v, i)}>
                                    <div className='left'>
                                        <img className='check' src={v.checked ? checked : check} />
                                        <p>{v.label}</p>
                                    </div>
                                    <span className='btn' onClick={(e)=>goNext(e, v)}><img className='next' src={next} />展开</span>
                                </div>)
                            }
                            {
                                type === 'person' && personList.map((v, i)=><div className='checkboxItem flexBox' onClick={()=>onCheckSelectChange(v, i)}>
                                    <img className='check' src={v.checked ? checked : check} />
                                    <Image preview={false} src={`${ossUrl}${v.logo}`} onError={(e)=>console.log(e)} className='head' />
                                    {v.userName || '-'}
                                </div>)
                            }
                        </div>
                    </div>
                    {/* 底部按钮 */}
                    <div className='foot'>
                        <Button onClick={onCancel}>取消</Button>
                        <Button type="primary" onClick={onOk}>确定（{selectPersonList.length}）</Button>
                    </div>
                </div>
            </div>
        </Modal>
    );
};

export default connect(({ common }) => ({ common }))(SelectPerson);
